package threads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Package: threads
 * Description： TODO
 * Author: Forest
 * Date: Created in 2021/4/8 13:55
 * Version: 0.0.1
 * Modified By: duforest
 */
public class DemoThread {
    // 多线程下共享变量标识位（可见性、有序性）
    private volatile AtomicBoolean isSucess = new AtomicBoolean(true);
    private static BlockingQueue<Runnable> workQueue = new DelayQueue();
    private static BlockingQueue<Runnable> workQueue1 = new LinkedBlockingDeque<>();
    //非公平锁
    private static BlockingQueue<Runnable> workQueue2 = new ArrayBlockingQueue<>(1);
    //公平锁
    private static BlockingQueue<Runnable> workQueue2_1 = new ArrayBlockingQueue<>(2, true);
    private static BlockingQueue<Runnable> workQueue3 = new SynchronousQueue<>();
    private static BlockingQueue<Runnable> workQueue4 = new PriorityBlockingQueue<>();
    private final static ThreadPoolExecutor executor = new ThreadPoolExecutor(1,
            1,
            2000,
            TimeUnit.MILLISECONDS,
            workQueue3,
            new HandleThreadFactory());
    private final static ThreadPoolExecutor executor2 = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
            60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(),
            new HandleThreadFactory());


    public static void main(String[] args) {
//        demo1();
        DemoThread demoThread = new DemoThread();
        try {
            demoThread.demo2();
        } catch (Exception e) {
            System.out.println("adahdjhashd" + e);
        }


    }

    private static void demo1() {
        ExecutorService exec = Executors.newCachedThreadPool(new HandleThreadFactory());
        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        exec.execute(new ThreadExceptionRunner(atomicBoolean));
        exec.shutdown();
        // 此处atomicBoolean.get()还是true
        System.out.println(atomicBoolean.get());
        System.out.println("main thread=" + Thread.currentThread().getName());
    }

    /**
     *
     */
    private void demo2() {
        ExecutorService exec = Executors.newFixedThreadPool(2);
//        executor2.execute(new ThreadExceptionRunner(isSucess));
        executor.execute(new ThreadExceptionRunner(isSucess));
        executor.shutdown();
        // 此处atomicBoolean.get()是false，因为使用了volatile修饰，标识线程之间可见性和有序性
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("sub reading,isSucess=" + !isSucess.get());
                if (!isSucess.get()) {
                    System.out.println("sub thread=" + Thread.currentThread().getName());
                }
            }
        }).start();

        if (isSucess.get()) {
            System.out.println("demo2 main=" + isSucess.get());
        }


    }


}
